<?php

namespace app\common\business;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class FeedBack
{
    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\FeedBack();
    }

    /**
     * @param $where
     * @param $page
     * @param $limit
     * @param string $field
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getListByWhere($where,$page,$limit,$field='*'){
        //$where[] = ['status','=',config("status.mysql.table_normal")];

        if ($page!=0 && $limit !=0){
            $list = $this->model->getPageListByWhere($where,$page,$limit,$field);
        }else{
            $list = $this->model->getNormalListByWhere($where,$field);
        }
        if($list->isEmpty()){
            return [];
        }
        return $list->toArray();
    }

    /**
     * 获取意见反馈列表
     * @param $data
     * @param $page
     * @param $limit
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getJoinPageList($data,$page,$limit){
        //$where[]=['work.status','=',config("status.mysql.table_normal")];
        $mapUser = [];
        $keyword = $data['keyword'];
        !empty($keyword) && $mapUser[] = ['user.name|user.phone_number','like','%'.$keyword.'%'];

        $bField='id,name,phone_number,sex,avatar';
        $list=$this->model::hasWhere('user',$mapUser)->field(['feedBack.id','feedBack.user_id','feedBack.content','feedBack.create_time'])->with(['user'=>function($query) use ($bField){
            $query->field($bField);
        }])->page($page,$limit)->order('id desc')->select();
        $list=$list->isEmpty()?[]:$list->toArray();

        $total=$this->model::hasWhere('user',$mapUser)->field(['feedBack.id'])->with(['user'=>function($query) use ($bField){
            $query->field($bField);
        }])->count();
        return ['list'=>$list,'count'=>$total];
    }

    /**
     * 新增/保存数据
     * @param $data
     * @return bool
     * @throws Exception
     */
    public function save($data): bool
    {
        if(empty($data['id'])){
            unset($data['id']);
        }
        return $this->model->saveData($data);
    }

    /**
     * 根据id删除
     * @param $id
     * @return bool
     * @throws Exception
     */
    public function deleteById($id): bool
    {
        if(empty($id)){
            throw new Exception('参数错误');
        }
        return $this->model->deleteById($id);
    }
}
